#include "TcpServer.hpp"
#include "Protocal.hpp"
#include <memory>

using namespace ns_tcpserver;
using namespace ns_protocol;

static void Usage(const std::string &process)
{
    std::cout << "\nUsage: " << process << " port\n"
              << std::endl;
}

Respense calculatorHelper(const Request& req)
{
    Respense resp(0, 0);
    switch (req.op_)
    {
    case '+':
        resp.result_ = req.x_ + req.y_;
        break;
    case '-':
        resp.result_ = req.x_ - req.y_;
        break;
    case '*':
        resp.result_ = req.x_ * req.y_;
        break;
    case '/':
        if (req.y_ == 0) resp.code_ = 1;
        else resp.result_ = req.x_ / req.y_;

        break;
    case '%':
        if (req.y_ == 0) resp.code_ = 2;
        else resp.result_ = req.x_ % req.y_;
        break;
    default:
        resp.code_ = 3;
        break;
    }

    return resp;
}

void calculator(int sock)
{
    while (true)
    {
        std::string str = Recv(sock); // 这里读到了一个请求
        Request req;
        req.Deserialized(str); // 反序列化
        Respense resp = calculatorHelper(req);
        std::string respString = resp.Serialize(); // 对计算结果进行序列化
        Send(sock, respString);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::unique_ptr<TcpServer> server(new TcpServer(atoi(argv[1])));
    server->BindService(calculator);
    server->start();


    // Request req(123, 456, '+');
    // std::string s = req.Serialize();
    // std::cout << s << std::endl;

    // Request temp;
    // temp.Deserialized(s);
    // std::cout << temp.x_ << std::endl;
    // std::cout << temp.op_ << std::endl;
    // std::cout << temp.y_ << std::endl;

    return 0;
}